#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include <stdarg.h>
#include <time.h>

int main(int argc, char *argv[]) {

mpf_t ak1,ak, bk, pk, sq;
mpf_t comp1, comp2;
int i;
clock_t begin, end;

  FILE *f = fopen("pi_borwein_seq.txt","w+");

  if(f == NULL) {
    return EXIT_FAILURE;
  }

	mpf_init2(ak, 40000000);
	mpf_init2(ak1, 40000000);
	mpf_init2(bk, 40000000);
	mpf_init2(pk, 40000000);
	mpf_init2(sq, 40000000);
	mpf_init2(comp1, 40000000);
	mpf_init2(comp2, 40000000);

  begin = clock();
	//iniciando a0
	mpf_sqrt_ui(ak, 2);
	
	//iniciando o b0
	//mpf_set_d(bk, 0.0);

	//iniciando o p0
	mpf_add_ui(pk, ak, 2);


	for(i = 0; i < 22; i++){
		//calculando o ak+1
		mpf_sqrt(sq, ak);
		mpf_ui_div(comp2, 1, sq);
		mpf_add(comp1, sq, comp2);

		mpf_div_ui(ak1, comp1, 2);

		//calculando o bk+1
		mpf_add_ui(comp1, bk, 1);
		mpf_mul(comp1, comp1, sq);
		mpf_add(comp2, ak, bk);
		
		mpf_div(bk, comp1, comp2);

		//calculando o pk+1
		mpf_add_ui(comp1, ak1, 1);
		mpf_mul(comp1, comp1, pk);
		mpf_mul(comp1, comp1, bk);
		mpf_add_ui(comp2, bk, 1);

		mpf_div(pk, comp1, comp2);

		mpf_set(ak, ak1);

    mpf_out_str(f,10,0,pk);
    fprintf(f,"\n");
			
	}
  end = clock();

  printf("Tempo do cálculo: %lf\n",(double)(end - begin)/CLOCKS_PER_SEC);

  fclose(f);


	mpf_clear(ak);
	mpf_clear(bk);	
	mpf_clear(pk);
	mpf_clear(sq);
	mpf_clear(comp1);
	mpf_clear(comp2);
	mpf_clear(ak1);

  return 0;
}
